<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/7
 * Time: 16:04
 */

namespace app\wap\controller;

use think\Controller;
use think\Db;
use think\Exception;
use app\wap\controller\Notify as Notify;

class Custom extends Controller
{
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
    }
    //定制接口 出发地
    public function origin(){
        $status_code=0;
        $msg='获取数据成功';

        try{
            $Dbcity=Db::name('city');  //城市
            //获取出发城市: 因数据库主要是目的地,先写几个范围大的，和几个主要城市， 中国大陆、台湾、香港、北美
            $city_China = $Dbcity->where(['groupid'=>65])->field('id,name,eng_name')->select();
            $origin=[
                [
                    'id'=>65,
                    'name'=>'中国',
                    'eng_name'=>'China',
                    'city'=>$city_China
                ]
            ];
        }catch (Exception $e){
            $status_code=2;
            $msg='获取数据失败';
        }

        if(empty($origin)){
            $status_code=3;
            $msg='未获取到数据';
        }
        $arr=['code'=>$status_code,'msg'=>$msg,'data'=>$origin];
        return json_encode($arr);
    }

    //定制接口 服务项目
    public function custom(){
        $status_code=0;
        $msg='获取数据成功';
        $Dbcustom=Db::name('custom_config');  //业务
        $custom=[];

        try{
            $custom_title_list=$Dbcustom->where(['pid'=>0,'type'=>1])->select();
            if(!empty($custom_title_list)){
                foreach ($custom_title_list as $k){
                    $custom_title_answer=$Dbcustom->where(['pid'=>$k['id']])->field('title as name')->select();
                    if(empty($custom_title_answer)){
                        continue;
                    }

                    //前端需要selsect字段 ，进行追加
                    foreach ($custom_title_answer as $key=>$value){
                        $custom_title_answer[$key]['select']=false;
                    }
                    //整理服务
                    $temp=[
//                        'id'=>$k['id'],
                        'title'=>$k['title'],
                        'type'=>empty($k['customtype'])?1:$k['customtype'], //为空时，默认为1，
                        'opts'=>$custom_title_answer
                    ];
                    array_push($custom,$temp);
                }
            }
        }catch (Exception $e){
            $status_code=2;
            $msg='获取数据失败';
        }

        if(empty($custom)){
            $status_code=3;
            $msg='未获取到数据';
        }
        $arr=['code'=>$status_code,'msg'=>$msg,'data'=>$custom];
        return json_encode($arr);
    }

    //定制接口 目的地
    public function destination(){
        $status_code=0;
        $msg='获取数据成功';
        $Dbcity=Db::name('city');  //城市

        try{
            //目的地城市:目的地只需要包含美国(id=48)及加拿大(id=51)城市
            $city_America = $Dbcity->where(['groupid'=>48])->field('id,name')->select();
            $city_Canada = $Dbcity->where(['groupid'=>51])->field('id,name')->select();
            $destination=[
                [
                    'id'=>48,
                    'name'=>'美国',
                    'city'=>[
                        'id'=>48,
                        'name'=>'美国',
                        'city'=>$city_America
                    ]
                ],
                [
                    'id'=>51,
                    'name'=>'加拿大',
                    'city'=>[
                        'id'=>51,
                        'name'=>'加拿大',
                        'city'=>$city_Canada
                    ]
                ]
            ];
        }catch (Exception $e){
            $status_code=2;
            $msg='获取数据失败';
        }

        if(empty($destination)){
            $status_code=3;
            $msg='未获取到数据';
        }
        $arr=['code'=>$status_code,'msg'=>$msg,'data'=>$destination];
        return json_encode($arr);
    }

    //定制接口 保存数据
    public function index(){
        $arr=['code'=>1,'msg'=>'提交失败,使用post提交'];
        if($this->request->isPost()){
            $post=$this->request->post();

            unset($post['token']);
            $post['service'] = json_encode($post['service']);
            //补充状态
            $post['status'] = 1; //待定制
            $post['createtime'] = time(); //待定制

            $match_arr = array("classId","service","status","username","phoneCode","phone","createtime","tagName","remarks","company");
            $match_res = $this->match_post($match_arr,$post);
            if($match_res['code']==200){
                $data_list=[
                    "classId"=>$post['classId'],
                    "service"=>$post['service'],
                    "status"=>$post['status'],
                    "username"=>$post['username'],
                    "phoneCode"=>$post['phoneCode'],
                    "phone"=>$post['phone'],
                    "createtime"=>$post['createtime'],
                    "tagName"=>$post['tagName'],
                    "remarks"=>$post['remarks'],
                    "company"=>$post['company'],
                ];
                $res=Db::name('custom')->insert($data_list);
                if($res){
                    $notify = new Notify();
                    $subject='新定制需求 '.$post['phoneCode'].$post['phone'];
                    $content='<p>定制申请人：'.$post['username'].'</p><p>申请日期：'.date('Y-m-d H:i:s',$post['createtime']).'</p><p>申请人联系方式：'.$post['phoneCode'].$post['phone'].'</p><p>目的地：'.$post['tagName'].'</p><p>备注：'.$post['remarks'].'</p>';
                    if(!empty($post['service'])){
                        $service_de=json_decode($post['service']);
                        foreach ($service_de as $l){
                             $content=$content.'<p>'.$l->title.':'.$l->val.'</p>';
                        }
                    }

                    $address='chris@kuaibangxing.com,david@kuaibangxing.com';
                    $notify->kbxemailcode($subject,$content,$address);
                    $arr['code'] = 0;
                    $arr['msg']='提交成功';
                }else{
                    $arr['msg']='提交成功,保存失败';
                }
            }else{
                $arr['msg']='字段缺失或不符合,'.$match_res['missKey'];
            }
        }
        return json_encode($arr);
    }

    public function match_post($match_arr=array(),$post=array())
    {
        if(!empty($post)){
            $key = array_keys($post);
            foreach($match_arr as $value){
                if(!in_array($value,$key)){//POST数组中不存在要求的key时
                    return array('code'=>400,'missKey'=>$value);
                }
            }
        }else{
            return array('code'=>401,'missKey'=>'');
        }
        return array('code'=>200,'missKey'=>'');
    }
}